#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2019/11/23  19:14
# @Author: 余浪人
# @email: yulangren520@gmail.com
import random
from datetime import datetime
from apps.models.separate_model import TL_Separate_Model
from apps.webapp import webapp_bp, render_theme, Authority
from flask import render_template, request,jsonify,url_for,make_response,abort
from apps.models.content_model import TL_Content_Model, TL_Comment_Model, db, TL_Column_model
from apps.webapi.webpublic.public import ipAdd, content, page_auto, notNull, conmmentAuthority, nav_list, img
from apps.lib.public import visiting_user, static_html, static_list_html, check_obj
from apps.lib.cache_sys import sys_cache, cache, column_cache, random_content, carousel_cache, clickRanking_cache, rec_content, notice_cache, hot_tags, links_cache, roll_text


@webapp_bp.context_processor
def inject_user():
    topNow = TL_Content_Model.query.order_by(TL_Content_Model.is_index_stick.desc()).order_by(TL_Content_Model.id.desc()).filter(TL_Content_Model.status == 1,TL_Content_Model.update_time < datetime.now())
    data, page = page_auto(topNow, 20, 4)
    public = {
        'system': sys_cache(),
        'column': column_cache(),  # 分类导航
        'lantern': content(carousel_cache()),  # 轮播
        'roll': content(roll_text()[:50], '%Y-%m-%d'),  # 滚动
        'topNew': {'data': content(data, '%Y-%m-%d'), 'page': page},  # 最新
        'ran_doc': content(random_content(), '%Y-%m-%d'),  # 随机推荐
        'blogroll': links_cache(),  # 友情链接
        'click_doc': content(clickRanking_cache(), '%Y-%m-%d'),  # 点击排行
        'notice': notice_cache(),  # 公告
        'con_rec': content(rec_content(), '%Y-%m-%d'),  # 推荐
        'tags': hot_tags()
    }
    return dict(public=public)

@webapp_bp.route('/', endpoint='index_page', methods=['GET'])
@Authority
@ipAdd
@visiting_user
@static_html
# @cache.cached(timeout=24 * (60 * 60), key_prefix='index_page')
def index_page(): return render_theme('index.html')

@webapp_bp.route('/list_article/<cid>.html', endpoint='list_article_page', methods=['GET'])
@Authority
@ipAdd
@visiting_user
@static_list_html
@cache.cache_with_param()
def list_article_page(cid):

    column = TL_Column_model.query.filter_by(uuid=cid).first()  # 当前分类
    if not check_obj(column): pass
    contList = TL_Content_Model.query.order_by(TL_Content_Model.is_list_stick.desc()).order_by(TL_Content_Model.id.desc()).filter(TL_Content_Model.status == 1, TL_Content_Model.superior == column.id)
    dataList, page = page_auto(contList, 10)  # 一页10条
    current_column = {
        'column_find': nav_list(TL_Column_model.query.filter(TL_Column_model.column_parent_id == column.id).all(),column.column_parent_id),'column': column,
        'page': {"total": page.total, "prev": page.has_prev, "prevPage": notNull(page.prev_num), "next": page.has_next, 'nextPage': notNull(page.next_num), 'currentPage': page.page,
                 'pages': page.pages, 'iter_pages': [pg for pg in page.iter_pages(2, 2, 2, 2) if pg]},
        'dataList': content(dataList, '%Y-%m-%d')
    }
    return render_theme('list_article.html', tlcms_column=current_column)


@webapp_bp.route('/article_page/<uid>.html', endpoint='article_page', methods=['GET'])
@Authority
@ipAdd
@visiting_user
@static_html
@cache.cache_with_param()
def article_page(uid):
    detail = TL_Content_Model.query.filter_by(uuid=uid, status=1).first()
    if not check_obj(detail): pass
    data_s = detail.pro.content_model
    num = 2 if len(data_s) >= 2 else len(data_s)
    page = random.sample(data_s, num)  # 实现上下页
    if len(page) == 2:
        next_page = {
            "title": page[0].title,
            "ID": page[0].uuid,
            'imgUrl': img(page[0].thumb_img, page[0].content),
        }
        last_page = {
            "title": page[1].title,
            "ID": page[1].uuid,
            'imgUrl': img(page[1].thumb_img, page[1].content),
        }
    elif len(page) == 1:
        next_page = {
            "title": page[0].title,
            "ID": page[0].uuid,
            'imgUrl': img(page[0].thumb_img, page[0].content),
        }
        last_page = {"title": '', "ID": '', 'imgUrl': '', }
    else:
        next_page = {"title": '', "ID": '', 'imgUrl': ''}
        last_page = {"title": '', "ID": '', 'imgUrl': ''}
    content_data = {
        "similar": content(detail.pro.content_model[:20][::-1], '%Y-%m-%d'),
        "data": {
            "title": detail.title,
            'ID': detail.uuid,
            'update_time': detail.update_time.strftime('%Y-%m-%d'),
            'title_color': detail.title_color,
            'imgUrl': img(detail.thumb_img, detail.content),
            'PID': detail.pro.column_name,
            'PID_Id': detail.pro.uuid,  # 分类ID
            'author': detail.author,
            'clicks': detail.clicks,
            'contributor': detail.contributor,
            'description': detail.description,
            'content': detail.content,
            'permissions': detail.permissions,
            'download': detail.download,
            'keyword': [i for i in detail.keyword.split(',') if i.strip()],
            'is_focus': detail.is_focus,
            'is_roll': detail.is_roll,
            'is_roll_text': detail.is_roll_text,
            'is_index_stick': detail.is_index_stick,
            'is_list_stick': detail.is_list_stick,
            'pay': detail.reward,
            'current_obj': detail
        },
        "commentList": [{
            "comment_txt": da.comment_txt,
            "user_qq": da.user_qq,
            "user_name": da.user_name,
            "create_time": da.create_time.strftime('%Y-%m-%d'),
        } for da in (detail.comment_model[:100])[::-1] if da.status],
        'comment_total': len(detail.comment_model),
        "next_page": next_page,
        "last_page": last_page,
    }
    return render_theme('article_article.html', tlcms_content=content_data)


@webapp_bp.errorhandler(404)
def not_found_error(error):
    return render_template('error_template/error_400.html'), 200


# 搜索
@webapp_bp.route('/search.html', endpoint='search', methods=['GET'])
@Authority
@ipAdd
@visiting_user
@cache.cache_with_param()
def search():
    keywords = request.args.get('keywords', '')
    contList = TL_Content_Model.query.order_by(TL_Content_Model.is_list_stick.desc()).order_by(TL_Content_Model.id.desc()).filter(TL_Content_Model.status == 1,TL_Content_Model.title.like(f"%{keywords}%"))
    dataList, page = page_auto(contList, 10 )  # 一页10条
    search = {
        'search': keywords,'dataList': content(dataList, '%Y-%m-%d'),
        'page': {
            "total": page.total, "prev": page.has_prev, "prevPage": notNull(page.prev_num), "next": page.has_next,
            'nextPage': notNull(page.next_num),'currentPage': page.page, 'pages': page.pages,
            'iter_pages': [pg for pg in page.iter_pages(2, 2, 2, 2) if pg]}
    }
    return render_theme('search_article.html', tlcms_search=search)


@webapp_bp.route('/tag/<string:tag>.html', endpoint='tag_page', methods=['GET'])
@Authority
@ipAdd
@cache.cache_with_param()
def tagIndex(tag):
    contList = TL_Content_Model.query.order_by(TL_Content_Model.is_list_stick.desc()).order_by(TL_Content_Model.id.desc()).filter(TL_Content_Model.status == 1,
                                                                                                                                  TL_Content_Model.title.like(f"%{tag}%"))
    dataList, page = page_auto(contList, 10, )
    tags = {
        'tag': tag,
        'page': {
            "total": page.total, "prev": page.has_prev, "prevPage": notNull(page.prev_num), "next": page.has_next, 'nextPage': notNull(page.next_num),
            'currentPage': page.page, 'pages': page.pages, 'iter_pages': [pg for pg in page.iter_pages(2, 2, 2, 2) if pg]},
        'dataList': content(dataList, '%Y-%m-%d')
    }
    return render_theme('tags_article.html', tlcms_tlcms=tags)


@webapp_bp.route('/comment_add/<uid>', endpoint='comment_add', methods=['POST'])
@Authority
@ipAdd
@visiting_user
@conmmentAuthority
def comment_add(uid):
    detail = TL_Content_Model.query.filter_by(uuid=uid, status=1).first()
    if detail is None: return jsonify({"status": 400, "message": "参数有误,验证失败!"})
    comment_txt = request.form.get('comment_txt')
    if comment_txt and not len(comment_txt) >= 5: return jsonify({"status": 406, "msg": "内容长度不足!"})
    user_qq = request.form.get('user_qq')
    user_name = request.form.get('user_name')
    obj = TL_Comment_Model()
    try:
        obj.set_attrs({"comment_txt": comment_txt, "content_uuid": uid, "user_qq": user_qq, "user_name": user_name})
        db.session.add(obj)
        db.session.commit()
    except:
        db.session.rollback()
        return jsonify({"status": 1, "msg": "评论发布失败!"})
    cache.delete(f'view/{request.host_url}article_page/{uid}')
    return jsonify({'status':0,'msg':'发布成功'})


@webapp_bp.route('/sitemap.xml', endpoint='sitemap', methods=['GET'])
@Authority
@ipAdd
@visiting_user
@cache.cached(timeout=12 * (60 * 60), key_prefix='sitemap_page')
def sitemap():
    header = '<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n'
    footer = '\n</urlset>'
    body = ''
    contents=TL_Content_Model.query.order_by(TL_Content_Model.id.desc()).filter(TL_Content_Model.update_time < datetime.now()).all()
    for cont in contents:body += f"\n<url>\n<loc>{url_for('webapp_bp.article_page',uid=cont.uuid)}</loc>\n<lastmod>{cont.update_time.strftime('%Y-%m-%d') }</lastmod>\n</url>"
    sitemap = header + body + footer
    response=make_response(sitemap)
    response.headers["Content-type"] = "text/xml"
    return response


@webapp_bp.route('/article/<regex("[a-zA-Z]+"):path>.html', endpoint='separate_article', methods=['GET'])
@Authority
@ipAdd
@visiting_user
@cache.cache_with_param(timeout=24 * (60 * 60))
def separate_article(path):
    se = TL_Separate_Model.query.filter_by().first()
    if se is None:return abort(404)
    if path=='about':
        separate = {'path':'about','pageName':'关于我们','code':se.about_page}
    elif path=='contact':
        separate = {'path': 'contact', 'pageName': '联系我们', 'code': se.contact_page}
    elif path=='copyright':
        separate = {'path': 'copyright', 'pageName': '版权说明', 'code': se.copyright_page}
    elif path=='cooperation':
        separate = {'path': 'cooperation', 'pageName': '商务合作', 'code': se.cooperation_page}
    else:
        return abort(404)
    return render_theme('separate_article.html',tlcms_separate=separate)